package com.yds.dccjll.lib.base.webview;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.yds.dccjll.lib.base.R;
import com.yds.dccjll.lib.base.util.FileUtil;
import com.yds.dccjll.lib.base.util.PermisstionUtil;


public class WebViewActivity extends Activity implements ReWebChomeClient.OpenFileChooserCallBack {

    public static Boolean isAlive = false;
    // 缓存路径
    private String appCachePath = "/webcache";
    // 是否是Https
    public static Boolean isHttp = false;

    public WebView mWebView;
    public Context mContext;
//    private PictureUtil2 pictureUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        mContext = this;
        initView();
        isAlive = true;
        clearWebViewCache();
        initKeyListener();
//        pictureUtil = new PictureUtil2(this, this);
    }

    private void initView() {
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_webview);
        mWebView = new WebView(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView.setLayoutParams(params);

        initWebViewSetting();
        mWebView.setWebChromeClient(new ReWebChomeClient(mContext, this));
        mWebView.setWebViewClient(new ReWebViewClient(mContext, mWebView, isHttp));
        linearLayout.addView(mWebView);
    }

    /**
     * 初始化webview设置
     */
    private void initWebViewSetting() {
        //设置缩放
        mWebView.getSettings().setSupportZoom(false);
        //设置允许访问文件
        mWebView.getSettings().setAllowFileAccess(true);
        //设置保存表单数据
        mWebView.getSettings().setSaveFormData(true);
        //设置是否使用viewport
        mWebView.getSettings().setUseWideViewPort(false);
        //设置WebView标准字体库字体，默认"sans-serif"
        mWebView.getSettings().setStandardFontFamily("sans-serif");
        //设置WebView固定的字体库字体，默认"monospace"
        mWebView.getSettings().setFixedFontFamily("monospace");
        //设置WebView是否以http、https方式访问从网络加载图片资源，默认false
        mWebView.getSettings().setBlockNetworkImage(false);
        //设置WebView是否从网络加载资源，Application需要设置访问网络权限，否则报异常
        mWebView.getSettings().setBlockNetworkLoads(false);
        //设置WebView是否允许执行JavaScript脚本
        mWebView.getSettings().setJavaScriptEnabled(true);
        //设置WebView运行中的脚本可以是否访问任何原始起点内容，默认true
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(false);
        //设置Application缓存API是否开启，默认false
        mWebView.getSettings().setAppCacheEnabled(true);
        //设置当前Application缓存文件路径
        mWebView.getSettings().setAppCachePath(appCachePath);
        //设置是否开启数据库存储API权限
        mWebView.getSettings().setDatabaseEnabled(true);
        //设置是否开启DOM存储API权限
        mWebView.getSettings().setDomStorageEnabled(true);
        //设置是否开启定位功能，默认true，开启定位
        mWebView.getSettings().setGeolocationEnabled(true);
        //设置脚本是否允许自动打开弹窗，默认false，不允许
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        //设置WebView加载页面文本内容的编码，默认“UTF-8”。
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        // 设置缓存模式
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置WebView是否自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        } else {
            mWebView.getSettings().setLoadsImagesAutomatically(false);
        }
        //硬件加速器的使用
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        try {
//            pictureUtil.OnActivityResult(requestCode, resultCode, data);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    protected ValueCallback<Uri> mUploadMsg;

    // 文件选择回调
    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
//        mUploadMsg = uploadMsg;
//        PermisstionUtil.requestPermissions(mContext, new String[]{PermisstionUtil.CAMERA},
//            PermisstionUtil.CAMERA_CODE, getString(R.string.permission_camera),
//            new PermisstionUtil.OnPermissionResult() {
//            @Override
//            public void granted(int requestCode) {
//                View parentView = getWindow().getDecorView().findViewById(android.R.id.content);
//                pictureUtil.loadPopup(mContext, parentView, new PictureUtil2.OnPopDismiss() {
//                    @Override
//                    public void dismiss(Boolean flag) {
//                        if (flag) {
//                            if (mUploadMsg != null) {
//                                mUploadMsg.onReceiveValue(null);
//                                mUploadMsg = null;
//                            }
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void denied(int requestCode) {
//                ToastUtil.showToast(getString(R.string.permission_camera_denied));
//            }
//        });

    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {
        // 清理WebView缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
            mWebView.clearCache(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileUtil.deleteFile(getCacheDir() + appCachePath);
//        FileUtil.deleteFile(PictureUtil2.path);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    protected void onDestroy() {
        isAlive = false;
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.destroy();
            mWebView = null;
            mContext = null;
        }
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermisstionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void initKeyListener() {
        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    if (mWebView.canGoBack()) {
                        mWebView.loadUrl("javascript:pageBack();");
                    } else {
                        finish();
                    }
                    return true;
                }
                return false;
            }
        });
    }

}
